<?php

namespace App\Http\Middleware;

use Closure;
use Example\Models\OperationLog as Model;

class OperationLog
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (config('common.operation_log.switch')) {
            if (request()->method() !== 'GET') {
                $actions = config('common.operation_log.actions');
                $pathArray = explode('/', request()->path());
                $action = $actions[end($pathArray)] ?? '';
                $data = [
                    'path' => $request->path(),
                    'params' => $request->all(),
                    'action' => $action,
                    'operation_ip' => getRealIp($request->ip()),
                    'operation_id' => auth()->user()->id ?? 0,
                ];
                Model::create($data);
            }
        }

        return $next($request);
    }
}
